package org.http.servlet;


import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author andy
 */
@Slf4j
public class ServletProcessor {
    private static Map<String,Class> map = new HashMap<>();

    private static void register(Set<Class<?>> lsClass ){
        for (Class cls: lsClass) {
            Servlet annotation = (Servlet) cls.getAnnotation(Servlet.class);
            if(null != annotation){
                String[] names = annotation.value();
                for (String name:names) {
                    map.put(name,cls);
                }
            }
        }
    }

    public static void init(String... packageName){
        Reflections f = new Reflections(packageName);
        Set<Class<?>> typeClass = f.getTypesAnnotatedWith(Servlet.class, true);
        register(typeClass);
    }

    public static WebServlet getServlet(String serviceName){
        log.info("GetFilterName:{}", serviceName);
        WebServlet servlet = null;
        try {
            Class className =  map.get(serviceName);
            servlet = (WebServlet) className.getDeclaredConstructor().newInstance();
            log.info("InvokeFilter: {}", servlet.getClass().getName());
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return servlet;
    }

}

